package com.cloud.message.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.common.constants.IMConstants;
import com.cloud.common.domain.Result;
import com.cloud.entity.SysUser;
import com.cloud.message.entity.SysImGroupUser;
import com.cloud.message.entity.SysImMessage;
import com.cloud.message.mapper.SysImMessageMapper;
import com.cloud.message.service.ISysImGroupService;
import com.cloud.message.service.ISysImMessageService;
import com.cloud.service.RedisService;
import com.cloud.socket.WebSocketBuilder;
import com.cloud.user_info.service.ISysUserService;
import com.cloud.utils.SecurityUtils;
import com.cloud.utils.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * IM消息记录
 *
 * @author yzj
 * @since 2024-01-09
 */
@Service
public class SysImMessageServiceImpl extends ServiceImpl<SysImMessageMapper, SysImMessage> implements ISysImMessageService {

    @Resource
    private SysImMessageMapper sysImMessageMapper;

    @Resource
    private RedisService redisService;

    @Autowired
    private ISysImGroupService sysImGroupService;

    @Autowired
    private ISysUserService userService;

    /**
     * IM消息记录列表
     */
    @Override
    public List<SysImMessage> getSysImMessageList(SysImMessage imMessage) {
        imMessage.setSendId(SecurityUtils.getUserId());
        // 删除用户IM未读缓存
        if (StringUtils.isNotNull(imMessage.getReceiveId())) {
            String imPersonKey = IMConstants.imPerson + imMessage.getSendId();
            String groupId = String.valueOf(imMessage.getReceiveId());
            redisService.delHashKey(imPersonKey, groupId);
        }
        // 删除群组IM未读缓存
        if (StringUtils.isNotNull(imMessage.getGroupId())) {
            String imGroupKey = IMConstants.imGroup + imMessage.getSendId();
            String groupId = String.valueOf(imMessage.getGroupId());
            redisService.delHashKey(imGroupKey, groupId);
        }
        return sysImMessageMapper.getSysImMessageList(imMessage);
    }

    /**
     * IM消息记录新增
     */
    @Override
    public Result saveSysImMessage(SysImMessage imMessage) {
        imMessage.setSendTime(new Date());
        if (StringUtils.isNotNull(imMessage.getGroupId())) {
            // 获取群组用户列表
            List<SysImGroupUser> groupUserList = sysImGroupService.getImGroupUserList(imMessage.getGroupId());
            if (groupUserList.size() > 0) {
                for (SysImGroupUser imGroupUser : groupUserList) {
                    // 消息发送失败,增加群组未读消息数
                    String clientId = String.valueOf(imGroupUser.getUserId());
                    String groupId = String.valueOf(imGroupUser.getGroupId());
                    if (!WebSocketBuilder.sendOneMessage(clientId, imMessage.getContent())) {
                        String imGroupKey = IMConstants.imGroup + imGroupUser.getUserId();
                        redisService.incrHash(imGroupKey, groupId, 1);
                    }
                    String imGroupKey = IMConstants.imGroupLogs + imGroupUser.getUserId();
                    redisService.setHash(imGroupKey, groupId, imGroupUser);
                }
            }
        } else {
            // 消息发送失败,增加用户未读消息数
            String clientId = String.valueOf(imMessage.getSendId());
            String groupId = String.valueOf(imMessage.getReceiveId());
            if (!WebSocketBuilder.sendOneMessage(clientId, imMessage.getContent())) {
                String imPersonKey = IMConstants.imPerson + imMessage.getSendId();
                redisService.incrHash(imPersonKey, groupId, 1);
            }
            SysImGroupUser imGroupUser = new SysImGroupUser();
            SysUser userInfo = userService.selectUserById(imMessage.getReceiveId());
            if (StringUtils.isNotNull(userInfo)) {
                imGroupUser.setUserId(userInfo.getUserId());
                imGroupUser.setNickName(userInfo.getNickName());
                imGroupUser.setSex(userInfo.getSex());
                imGroupUser.setAvatar(userInfo.getAvatar());
                String imPersonKey = IMConstants.imPersonLogs + imMessage.getSendId();
                redisService.setHash(imPersonKey, groupId, imGroupUser);
            }
        }
        sysImMessageMapper.insert(imMessage);
        return Result.success("操作成功");
    }

    /**
     * IM消息记录删除
     */
    @Override
    public int removeIds(List<Long> ids) {
        return sysImMessageMapper.deleteBatchIds(ids);
    }

    /**
     * 获取IM消息记录列表
     */
    @Override
    public Result getMessageLogs() {
        List<SysImGroupUser> groupUserList = new ArrayList<>();
        String userId = String.valueOf(SecurityUtils.getUserId());
        // 获取对话群组列表
        Map<String, SysImGroupUser> groupUserMap = redisService.getHash(IMConstants.imGroupLogs + userId);
        if (StringUtils.isNotNull(groupUserMap)) {
            for (Map.Entry<String, SysImGroupUser> entry : groupUserMap.entrySet()) {
                // 获取用户群组未读消息数
                Map<String, Integer> groupMap = redisService.getHash(IMConstants.imGroup + userId);
                if (StringUtils.isNotNull(groupMap) && groupMap.containsKey(entry.getKey())) {
                    entry.getValue().setMessageNum(groupMap.get(entry.getKey()));
                }
                groupUserList.add(entry.getValue());
            }
        }
        // 获取对话用户列表
        Map<String, SysImGroupUser> personUserMap = redisService.getHash(IMConstants.imPersonLogs + userId);
        if (StringUtils.isNotNull(personUserMap)) {
            for (Map.Entry<String, SysImGroupUser> entry : personUserMap.entrySet()) {
                // 获取用户未读消息数
                Map<String, Integer> personMap = redisService.getHash(IMConstants.imPerson + userId);
                if (StringUtils.isNotNull(personMap) && personMap.containsKey(entry.getKey())) {
                    entry.getValue().setMessageNum(personMap.get(entry.getKey()));
                }
                groupUserList.add(entry.getValue());
            }
        }
        return Result.success("查询成功", groupUserList);
    }

    /**
     * 每天3点30分,清理IM消息记录
     */
    @Scheduled(cron = "0 30 3 * * ?")
    public void removeImLogs() {
        // 清空IM群组记录
        redisService.del(IMConstants.imGroupUser);
        // 清空IM消息记录
        redisService.del(IMConstants.imMessage);
    }

}
